import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:syncfusion_flutter_charts/sparkcharts.dart';

class SyncfusionChartsPage extends StatefulWidget {
  // ignore: prefer_const_constructors_in_immutables
  SyncfusionChartsPage({Key? key}) : super(key: key);

  @override
  SyncfusionChartsPageState createState() => SyncfusionChartsPageState();
}

class SyncfusionChartsPageState extends State<SyncfusionChartsPage> {
  List<_SalesData> data = [
    _SalesData('一月', 35.123,Colors.red),
    _SalesData('二月', 28,Colors.yellow),
    _SalesData('三月', 34,Colors.green),
    _SalesData('四月', 32,Colors.cyan),
    _SalesData('五月', 40,Colors.blue),
  ];

  List<_SalesData> data2 = [
    _SalesData('一月', 25.123,Colors.red),
    _SalesData('二月', 48,Colors.yellow),
    _SalesData('三月', 20,Colors.green),
    _SalesData('四月', 35,Colors.cyan),
    _SalesData('五月', 47,Colors.blue),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('同步融合Flutter图表'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(children: [
            Builder(
              builder: (context) {
                double angle = 0;
                return SfCircularChart(
                  // 图表标题
                    title: ChartTitle(
                        text: '半年销售分析',
                      textStyle:const TextStyle(color: Colors.black,fontSize: 12),
                      alignment: ChartAlignment.center,
                      borderWidth: 1,
                      borderColor: Colors.blue,
                      backgroundColor: Colors.white38
                    ),
                    // 启用说明
                    legend: Legend(
                      isVisible: true,
                      position:LegendPosition.bottom,
                    ),
                    // 启用提示工具Bar
                    tooltipBehavior: TooltipBehavior(
                        enable: true,
                        textStyle:const TextStyle(fontSize: 12,color: Colors.white),
                        ///激活方式
                        activationMode:ActivationMode.doubleTap,
                        ///动画时间
                        animationDuration:800,
                        borderColor:Colors.blue,
                        borderWidth:2,
                        shouldAlwaysShow:true,
                        //海拔
                        elevation:10,
                        canShowMarker:false,
                        textAlignment:ChartAlignment.near,
                        decimalPlaces:1,
                        tooltipPosition:TooltipPosition.auto,
                        shared:true,
                        color:Colors.green,
                        // header:"label",
                        format:"point.y %",
                        shadowColor:Colors.red,
                        // builder: (dynamic data, dynamic point, dynamic series, int? pointIndex, int? seriesIndex) {
                        //      return Container(
                        //       height: 50,
                        //        width: 100,
                        //        decoration:  const BoxDecoration(
                        //          color: Color.fromRGBO(66, 244, 164, 1),
                        //        ),
                        //          child: Text('pointIndex:$pointIndex seriesIndex:$seriesIndex')
                        //     );
                        //    }
                    ),
                    //背景颜色
                    backgroundColor:Colors.blueGrey,
                    //盘上注释
                    // annotations: data.map((e){
                    //   angle = angle+e.sales;
                    //   return CircularChartAnnotation(
                    //       angle: ((angle/(35+28+34+32+40))*360).toInt()-130,
                    //       radius: '100%',
                    //       widget: Text(e.year)
                    //   );
                    // }).toList(),
                    borderColor:Colors.blue,
                    borderWidth:2,
                    //中心坐标
                    // centerX: "100",
                    // centerY: "100",
                    selectionGesture:ActivationMode.longPress,
                    enableMultiSelection:true,
                    series: <CircularSeries>[
                      PieSeries<_SalesData, String>(
                        dataSource: data,
                        xValueMapper: (_SalesData data, int index) {
                          return data.year;
                        },
                        yValueMapper: (_SalesData data, int index) {
                          return data.sales;
                        },
                        pointColorMapper:(_SalesData data, int index){
                          return data.color;
                        },
                        // pointShaderMapper:(_SalesData data, int index, Color color, Rect rect){
                        //   Shader shader = Shader();
                        //   return shader;
                        // },
                        pointRadiusMapper:(_SalesData data, int index){
                          return "80";
                        },
                        dataLabelMapper:(_SalesData data, int index){
                          return data.year;
                        },
                        sortFieldValueMapper:(_SalesData data, int index){
                          return "1";
                        },
                        startAngle:0,
                        endAngle:360,
                        radius: "80",
                        explode: true,
                        // explodeAll:true,
                        explodeIndex:1,
                        explodeGesture:ActivationMode.doubleTap,
                        explodeOffset:"20",
                        groupTo:4,
                        groupMode:CircularChartGroupMode.point,
                        pointRenderMode:PointRenderMode.segment,
                        emptyPointSettings:EmptyPointSettings(
                          color: Colors.purpleAccent,
                          borderColor: Colors.brown,
                          borderWidth: 2,
                        ),
                        strokeColor:Colors.teal,
                        strokeWidth: 2,
                        opacity: 0.8,
                        dataLabelSettings: const DataLabelSettings(
                          isVisible: true,
                          // color: Colors.cyan,
                          useSeriesColor: true,
                          textStyle:TextStyle(fontSize: 12,color: Colors.blue),
                          alignment: ChartAlignment.center,
                          borderWidth:1,
                          overflowMode: OverflowMode.trim,
                            showZeroValue : true,
                            labelPosition: ChartDataLabelPosition.outside,
                          labelIntersectAction: LabelIntersectAction.shift,
                          connectorLineSettings: ConnectorLineSettings(
                              type: ConnectorType.curve,
                              width: 2,
                              color: Colors.redAccent,
                              length: '50',
                          )
                        ),
                        enableTooltip: true,
                        name: "text01",
                        animationDuration: 400,
                        animationDelay: 200,
                        selectionBehavior: SelectionBehavior(
                            selectedColor:Colors.pinkAccent,
                            selectedBorderColor:Colors.red,
                        ),
                        sortingOrder: SortingOrder.descending,
                        legendIconType: LegendIconType.triangle,


                        // initialSelectedDataIndexes:[0,1,2,3],
                        // onCreateRenderer:(ChartSeries<_SalesData, String> chartSeries){
                        //   ChartSeriesRenderer chartSeriesRenderer= ChartSeriesRenderer();
                        //   return chartSeriesRenderer;
                        // },
                        onRendererCreated:(CircularSeriesController circularSeriesController){
                          print("01===========渲染器创建:onRendererCreated ${circularSeriesController}");
                        },
                        onPointTap:(ChartPointDetails chartPointDetails){
                          print("02===========图表点详细信息:chartPointDetails ${chartPointDetails}");
                        },
                        onPointDoubleTap:(ChartPointDetails chartPointDetails){
                          print("03===========图表点详细信息:chartPointDetails ${chartPointDetails}");
                        },
                        onPointLongPress:(ChartPointDetails chartPointDetails){
                          print("04===========图表点详细信息:chartPointDetails ${chartPointDetails}");
                        },
                      ),

                      PieSeries<_SalesData, String>(
                        dataSource: data2,
                        // pointColorMapper:(_SalesData data, int index){
                        //   return data.color;
                        // },
                        xValueMapper: (_SalesData data2, int index) {
                          return data2.year;
                        },
                        yValueMapper: (_SalesData data2, int index) {
                          return data2.sales;
                        },
                      ),
                    ],
                    ///扇区颜色
                    palette:const [
                      Color(0xFF00FF00),
                      Color(0xFF0000FF),
                      Color(0xFFFFFF00),
                      Color(0xFFFF00FF),
                      Color(0xFF00FFFF),
                    ],
                  ///在图例项目渲染上
                  onLegendItemRender:(LegendRenderArgs legendRenderArgs){
                    print("0===========图例渲染参数:legendRenderArgs ${legendRenderArgs}");
                  },
                  ///在工具提示渲染上
                  onTooltipRender:(TooltipArgs tooltipArgs){
                    print("1===========工具提示参数:tooltipArgs ${tooltipArgs}");
                  },
                  ///在数据标签渲染上
                  onDataLabelRender:(DataLabelRenderArgs dataLabelRenderArgs){
                    print("2===========数据标签渲染参数:dataLabelRenderArgs ${dataLabelRenderArgs}");
                  },
                  ///在点击的数据标签上
                  onDataLabelTapped:(DataLabelTapDetails dataLabelTapDetails){
                    print("3===========数据标签点击详情:dataLabelTapDetails ${dataLabelTapDetails}");
                  },
                  ///关于点击图例
                  onLegendTapped:(LegendTapArgs legendTapArgs){
                    print("4===========图例点击参数:legendTapArgs ${legendTapArgs}");
                  },
                  ///选择已更改
                  onSelectionChanged:(SelectionArgs selectionArgs){
                    print("5===========选择参数:selectionArgs ${selectionArgs}");
                  },
                  ///在图表上抬起触摸互动
                  onChartTouchInteractionUp:(ChartTouchInteractionArgs chartTouchInteractionArgs){
                    print("6===========图表触摸交互参数:chartTouchInteractionArgs ${chartTouchInteractionArgs}");
                  },
                  ///在图表上向下触摸交互
                  onChartTouchInteractionDown:(ChartTouchInteractionArgs chartTouchInteractionArgs){
                    print("7===========图表触摸交互参数:chartTouchInteractionArgs ${chartTouchInteractionArgs}");
                  },
                  ///在图表上触摸交互移动
                  onChartTouchInteractionMove:(ChartTouchInteractionArgs chartTouchInteractionArgs){
                    print("8===========图表触摸交互参数:chartTouchInteractionArgs ${chartTouchInteractionArgs}");
                  },
                  // ///创建着色器
                  // onCreateShader:(ChartShaderDetails chartShaderDetails){
                  //   print("===========图表着色器详细信息:${chartShaderDetails}");
                  //   Shader shader = Shader();
                  //   return shader;
                  // },
                );
              }
            ),
            const SizedBox(height: 10,),
            SfCartesianChart(
                // 图表标题
                title: ChartTitle(text: '半年销售分析'),
                // 启用说明
                legend: customLegend(),
                backgroundColor: Colors.grey,
                borderWidth: 3,
                borderColor: Colors.black,
                plotAreaBackgroundColor: Colors.white38,
                plotAreaBorderColor: Colors.red,
                plotAreaBorderWidth: 3,
                primaryXAxis: CategoryAxis(
                  title: AxisTitle(
                    text: "titleX",
                  ),
                    name: "titleX",
                    isVisible: true,
                    axisLine: const AxisLine(
                      color:Colors.redAccent,
                      // dashArray:,
                      width:1,
                    ),
                    arrangeByIndex:false,
                    rangePadding: ChartRangePadding.additional,
                    labelPlacement:LabelPlacement.betweenTicks,
                    edgeLabelPlacement: EdgeLabelPlacement.shift,
                    labelPosition: ChartDataLabelPosition.outside,
                    tickPosition: TickPosition.outside,
                    labelRotation: 60,
                    // labelIntersectAction: true,
                    // labelAlignment: true,
                    // isInversed: true,
                    // opposedPosition: true,
                    // minorTicksPerInterval: true,
                    // maximumLabels: true,
                    // majorTickLines: true,
                    // minorTickLines: true,
                    // majorGridLines: true,
                    // minorGridLines: true,
                    // labelStyle: true,
                    // plotOffset: true,
                    // zoomFactor: true,
                    // zoomPosition: true,
                    // interactiveTooltip: true,
                    // minimum: true,
                    // maximum: true,
                    // interval: true,
                    // visibleMinimum: true,
                    // visibleMaximum: true,
                    // crossesAt: true,
                    // associatedAxisName: true,
                    // placeLabelsNearAxisLine: true,
                    // plotBands: true,
                    // desiredIntervals: true,
                    // rangeController: true,
                    // maximumLabelWidth: true,
                    // labelsExtent: true,
                    // autoScrollingDelta: true,
                    // borderWidth: true,
                    // borderColor: true,
                    // axisBorderType: true,
                    // multiLevelLabelFormatter: true,
                    // multiLevelLabelStyle: true,
                    // multiLevelLabels: true,
                    // autoScrollingMode: true,
                    // axisLabelFormatter: true,
                ),
                primaryYAxis: CategoryAxis(
                  title: AxisTitle(
                    text: "titleY",
                  ),
                ),
                margin:const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                // axes:[CategoryAxis(
                //   name: "z==",
                //   title: AxisTitle(
                //     text: "titleZ",
                //   ),
                // ), CategoryAxis(
                //     name: "w==",
                //     title: AxisTitle(
                //       text: "titleW",
                //     ),
                //   ),],
                // 启用工具提示
                tooltipBehavior: TooltipBehavior(enable: true),
                crosshairBehavior:CrosshairBehavior(),
                trackballBehavior:TrackballBehavior(),
                zoomPanBehavior:ZoomPanBehavior(),
                selectionType:SelectionType.point,
                // annotations:[
                //   CartesianChartAnnotation(
                //       widget: Container(
                //           child: const Text('Annotation')),
                //       coordinateUnit: CoordinateUnit.point,
                //       region: AnnotationRegion.chart,
                //       x: 3,
                //       y: 60
                //   ),
                //   CartesianChartAnnotation(
                //       widget: Container(
                //           child: const Text('Annotation')),
                //       coordinateUnit: CoordinateUnit.point,
                //       region: AnnotationRegion.chart,
                //       x: 3,
                //       y: 60
                //   ),
                // ],
                enableMultiSelection:true,
                selectionGesture:ActivationMode.doubleTap,
                // plotAreaBackgroundImage:true,
                isTransposed:false,
                enableAxisAnimation:true,
                series: <ChartSeries<_SalesData, String>>[
                  LineSeries<_SalesData, String>(
                      dashArray: <double>[5, 5],
                      dataSource: data,
                      ///x 值映射器
                      xValueMapper: (_SalesData sales, _) => sales.year,
                      ///y 值映射器
                      yValueMapper: (_SalesData sales, _) => sales.sales,
                      name: '销售量',
                      // 启用数据标签
                      dataLabelSettings: const DataLabelSettings(isVisible: true)),
                  LineSeries<_SalesData, String>(
                      dataSource: data2,
                      ///x 值映射器
                      xValueMapper: (_SalesData sales, _) => sales.year,
                      ///y 值映射器
                      yValueMapper: (_SalesData sales, _) => sales.sales,
                      pointColorMapper:(_SalesData data, _) => data.color,
                      name: '入货量',
                      // 启用数据标签
                      dataLabelSettings: const DataLabelSettings(isVisible: true),
                      markerSettings: const MarkerSettings(
                        isVisible: true,
                        borderColor:Colors.pinkAccent,
                        borderWidth:2,
                        color:Colors.greenAccent,
                        shape: DataMarkerType.diamond,
                      )
                  ),
                ],
                palette:const [
                  Color(0xFF00FF00),
                  Color(0xFF0000FF),
                  Color(0xFFFFFF00),
                  Color(0xFFFF00FF),
                  Color(0xFF00FFFF),
                ],
                  indicators: <TechnicalIndicators<_SalesData, num>>[
                    StochasticIndicator<_SalesData, num>(
                      isVisible: true
                    ),
                  ],
                // loadMoreIndicatorBuilder:(BuildContext context, ChartSwipeDirection chartSwipeDirection){
                //   return Container(
                //     width: 5,
                //     height: 5,
                //     color: Colors.red,
                //   );
                // },
                onPlotAreaSwipe:(ChartSwipeDirection chartSwipeDirection){
                  print("========chartSwipeDirection:${chartSwipeDirection}");
                },
              ///启用并排系列放置
              enableSideBySideSeriesPlacement:true,
              onTooltipRender:(TooltipArgs tooltipArgs){
                print("========工具提示参数:tooltipArgs:${tooltipArgs}");
              },
              onActualRangeChanged:(ActualRangeChangedArgs actualRangeChangedArgs){
                print("========实际范围更改参数:actualRangeChangedArgs:${actualRangeChangedArgs}");
              },
              onDataLabelRender:(DataLabelRenderArgs dataLabelRenderArgs){
                print("========数据标签渲染参数:dataLabelRenderArgs:${dataLabelRenderArgs}");
              },
              onLegendItemRender:(LegendRenderArgs legendRenderArgs){
                print("========图例渲染参数:legendRenderArgs:${legendRenderArgs}");
              },
              onTrackballPositionChanging:(TrackballArgs trackballArgs){
                print("========轨迹球参数:trackballArgs:${trackballArgs}");
              },
              onCrosshairPositionChanging:(CrosshairRenderArgs crosshairRenderArgs){
                print("========十字线渲染参数:crosshairRenderArgs:${crosshairRenderArgs}");
              },
              onZoomStart:(ZoomPanArgs zoomPanArgs){
                print("========开始缩放：zoomPanArgs:${zoomPanArgs}");
              },
              onZoomEnd:(ZoomPanArgs zoomPanArgs){
                print("========缩放结束：onZoomEnd:${zoomPanArgs}");
              },
              onZoomReset:(ZoomPanArgs zoomPanArgs){
                print("========重置缩放：onZoomReset:${zoomPanArgs}");
              },
              onZooming:(ZoomPanArgs zoomPanArgs){
                print("========缩放中：onZooming:${zoomPanArgs}");
              },
              onDataLabelTapped:(DataLabelTapDetails dataLabelTapDetails){
                print("========数据标签点击详情：dataLabelTapDetails:${dataLabelTapDetails}");
              },
              onAxisLabelTapped:(AxisLabelTapArgs axisLabelTapArgs){
                print("========轴标签点击参数 axisLabelTapArgs:${axisLabelTapArgs}");
              },
              onLegendTapped:(LegendTapArgs legendTapArgs){
                print("========图例点击参数：legendTapArgs:${legendTapArgs}");
              },
              onSelectionChanged:(SelectionArgs selectionArgs){
                print("========选择参数：selectionArgs:${selectionArgs}");
              },
              onChartTouchInteractionUp:(ChartTouchInteractionArgs chartTouchInteractionArgs){
                print("========图表触摸交互参数：chartTouchInteractionArgs:${chartTouchInteractionArgs}");
              },
              onChartTouchInteractionDown:(ChartTouchInteractionArgs chartTouchInteractionArgs){
                print("========图表触摸交互参数：chartTouchInteractionArgs:${chartTouchInteractionArgs}");
              },
              onChartTouchInteractionMove:(ChartTouchInteractionArgs chartTouchInteractionArgs){
                print("========图表触摸交互参数：chartTouchInteractionArgs:${chartTouchInteractionArgs}");
              },
              onMarkerRender:(MarkerRenderArgs markerRenderArgs){
                print("========标记渲染参数：markerRenderArgs:${markerRenderArgs}");
              },
            ),
            const SizedBox(height: 10,),
            SfSparkLineChart(
              data: const [4,2,6,5,3],
              dashArray: const [0.1,0.2,0.3,0.4,0.5],
              axisLineDashArray: const [0.1,0.2,0.3,0.4,0.5],
              // dataCount: 5,
              // xValueMapper: (int index) => data[index].year,
              // yValueMapper: (int index) => data[index].sales,
              ///火花图绘图带
              plotBand:const SparkChartPlotBand(
                  color:Color.fromRGBO(191, 212, 252, 0.5),
                  start:0,
                  end:2,
                  borderColor:Colors.blue,
                  borderWidth:2,
              ),
              color: Colors.brown,
              width:4,
              ///是否上下颠倒
              isInversed:false,
              //启用竖线轨迹球
              trackball: const SparkChartTrackball(
                  activationMode: SparkChartActivationMode.tap,
                  width:2,
                  color:Colors.red,
                  // dashArray:,
                  // activationMode:SparkChartActivationMode.tap,
                  // abelStyle:const TextStyle(fontFamily: 'Roboto', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 12),
                  // tooltipFormatter:(TooltipFormatterDetails tooltipFormatterDetails){
                  //   return "";
                  // },
                  backgroundColor:Colors.greenAccent,
                  shouldAlwaysShow:false,
                  hideDelay:200,
                  borderColor:Colors.amber,
                  borderWidth:5,
                  borderRadius:BorderRadius.all(Radius.circular(2)),
              ),
              //启用标记点
              marker: const SparkChartMarker(
                //火花图标记显示模式
                displayMode: SparkChartMarkerDisplayMode.all,
                borderColor:Colors.pinkAccent,
                borderWidth:2,
                color:Colors.greenAccent,
                size:20,
                shape:SparkChartMarkerShape.diamond,
              ),
              //启用数据标签
              labelDisplayMode: SparkChartLabelDisplayMode.all,
              labelStyle: TextStyle(fontSize: 20,color: Colors.purpleAccent),
              firstPointColor: Colors.red,
              negativePointColor: Colors.green,
              highPointColor: Colors.blue,
              lowPointColor: Colors.yellow,
              lastPointColor: Colors.pinkAccent,
              axisCrossesAt:0,
              axisLineColor:Colors.blueGrey,
              axisLineWidth:3,
            ),
            ]
          ),
        ),
      ),
    );
  }

  Legend customLegend(){
    return Legend(
      isVisible: true,
      position: LegendPosition.top,
      alignment: ChartAlignment.center,
      backgroundColor: Colors.black26,
      borderColor: Colors.grey,
      borderWidth: 1,
      opacity: 1.0,
      // height: "100",
      // width: "400",
      // padding: 10.0,
      iconHeight: 20,
      iconWidth: 20,
      shouldAlwaysShowScrollbar: true,
      toggleSeriesVisibility: true,
      textStyle: const TextStyle(color: Colors.yellow,fontSize: 15),
      isResponsive: true,
      orientation: LegendItemOrientation.vertical,
      title: LegendTitle(
        text:"各种参数",
        textStyle:const TextStyle(color: Colors.black,fontSize: 15),
        alignment: ChartAlignment.center,
      ),
      overflowMode: LegendItemOverflowMode.wrap,
      // legendItemBuilder: (String s, dynamic d, dynamic c, int i){
      //   ///自己画ItemBar
      //   return Container(
      //     width: 100,height: 20,color: Colors.transparent,
      //     child: Text("${s}"),
      //   );
      // },
      iconBorderColor: Colors.blueGrey,
      iconBorderWidth: 4,
      itemPadding: 10,
      offset: const Offset(0,10),
      // image: true,
    );
  }
}

class _SalesData {
  _SalesData(this.year, this.sales, this.color);
  final String year;
  final double sales;
  final Color color;
}